<?php

namespace Service;

use Entity\Sim;
use Doctrine\ORM\EntityManager;
use Entity\SimOwner;

class SimManager extends Manager
{
    protected function _getEntityClass()
    {
        return 'Sim';
    }
    
    public function delete($id)
    {
        if (!$this->getUser()->isAdmin()) {
            return;
        }
        parent::delete($id);
    }

    public function create(array $data)
    {
        $sim = parent::create($data);
        $user = $this->getUser();
        $user->addSim($sim);
        $this->_em->flush();
    }

    public function transferNumbers($idNumbers, $idUser)
    {
        $arrayIds = explode(",", $idNumbers);
        $qb = $this->_em->createQueryBuilder();
        $qb->select("so")
            ->from("Entity\SimOwner", "so")
            ->where($qb->expr()->in("so.id", $arrayIds));

        $sims = $qb->getQuery()->getResult();
        $agent = $this->_em->getRepository("Entity\User")->find($idUser);

        foreach ($sims as $sim) {
            /* @var $sim SimOwner */
            // $sim->setUser($agent);
            $simOwner = new SimOwner();
            $simOwner->setUser($agent);
            $simOwner->setSim($sim->getSim());
			$sim->setState(false);
            $this->_em->persist($simOwner);
        }

        $this->_em->flush();
    }

    public function isValidPhoneNumber($number)
    {
        $sim = $this->_em->getRepository("Entity\Sim")->findOneByNumber($number);
        return !is_object($sim);
    }
}